<template>
  <div class="container">
    <el-row type="flex" justify="space-between">
      <div style="display:inline-flex;flex:1;align-items: center;">
        <el-button @click="exportExcel" type="success" icon="el-icon-download">导出</el-button>
      </div>
      <div style="display:flex;flex:18;align-items: center">
        <el-date-picker
          :class="dateNull ? 'inputNull' : ''"
          @change="ruleInput(1)"
          v-model="form.date"
          style="margin-left: 1%;width: 30%;"
          type="daterange"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
        <span style="font-size: 14px;margin-left: 1%;width: 15%">告警次数大于: </span>
        <el-input-number v-model="form.intSettingThreshold" style="width: 25%" @change="ruleInput(2)"
                         :class="intSettingNull ? 'numberNull' : ''" controls-position="right">
        </el-input-number>
        <span style="font-size: 14px;margin-left: 1%;width: 10%">连续天数: </span>
        <el-input-number v-model="form.intFilteredThreshold" style="width: 25%" @change="ruleInput(3)"
                         :class="intFilteredNull ? 'numberNull' : ''" class="input-with-select" controls-position="right">
        </el-input-number>
      </div>
      <div style="display:flex;flex:2;" >
        <el-button style="margin-left: 10px" @click="queryData" type="primary" icon="el-icon-search">查询</el-button>
        <el-button style="margin-left: 10px" @click="clearFn" type="danger" icon="el-icon-delete">清除</el-button>
      </div>
    </el-row>

    <el-table :data="tableData" style="width: 100%;margin-top:15px;" :row-style="{height:'40px'}" border isIndex
              v-loading="tableLoading" element-loading-text="数据加载中，请耐心等待......" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.6)">
    <el-table-column prop="netCode" label="台网" align="center" fixed>
      </el-table-column>
      <el-table-column prop="chanCode" label="" align="center" style="justify-content: center">
        <template style="width: 100%">
          <el-row class="annotation-row">
            片区断记
          </el-row>
          <el-row class="annotation-row delay-row">
            片区延时
          </el-row>
        </template>
      </el-table-column>
      <el-table-column :label="item" align="center" show-overflow-tooltip v-for="(item, index) in tableTitle" :key="index">
        <template slot-scope="scope">
          <el-row class="annotation-row" :class="[scope.row.dataList[index].status === '红色' ? 'red' : '',
          scope.row.dataList[index].status === '绿色' ? 'green' : '', scope.row.dataList[index].status === '黄色' ? 'yellow' : '',
          scope.row.dataList[index].status === '蓝色' ? 'blue' : '']">
            {{scope.row.dataList[index].areaBreakNum == null  ? '-' : scope.row.dataList[index].areaBreakNum}}
          </el-row>
          <el-row class="annotation-row delay-row">
            {{scope.row.dataList[index].areaDelayNum == null  ? '-' : scope.row.dataList[index].areaDelayNum}}
          </el-row>
        </template>
      </el-table-column>
      <el-table-column label="总次数" align="center" show-overflow-tooltip fixed="right">
        <template slot-scope="scope">
          <el-row class="annotation-row">
            {{scope.row.areaBreakTotal}}
          </el-row>
          <el-row class="annotation-row delay-row">
            {{scope.row.areaDelayTotal}}
          </el-row>
        </template>
      </el-table-column>
    </el-table>

  </div>
</template>

<script>
import {
  getAlermData,
  getAllChanCode,
  getAllChanNum,
  getAllNetCode,
  getNetCode
} from '@/api'
import MiddleUtil from '@/utils/MiddleUtil'
export default {
  name: 'Home',
  data () {
    return {
      tableData: [],
      form: {
        date: ['2000-11-01', '2035-11-01'],
        intSettingThreshold: 1,
        intFilteredThreshold: 1
      },
      total: 0,
      netCode: [], // 台网码数组,用于sheet命名
      netCodeOptions: [],
      chanNumOptions: [],
      chanCodeOptions: [],
      tableTitle: [],
      // 数据加载
      tableLoading: false,
      dateNull: false,
      intSettingNull: false,
      intFilteredNull: false
    }
  },
  created () {
    const dateRange = this.getDefaultDate()
    this.form.date = [dateRange[0], dateRange[1]]
    this.getBaseData()
    this.getNetCode()
  },
  mounted () {
    const that = this
    MiddleUtil.$on('alarmExport', () => {
      that.exportDefaultExcel()
    })
  },
  methods: {
    ruleForm () {
      if (this.form.date === null) {
        this.dateNull = true
        this.$notify.info({
          title: '提示',
          message: '请输入日期'
        })
        return false
      }
      this.dateNull = false
      if (this.form.intSettingThreshold === undefined) {
        this.intSettingNull = true
        this.$notify.info({
          title: '提示',
          message: '请输入告警次数'
        })
        return false
      }
      this.intSettingNull = false
      if (this.form.intFilteredThreshold === undefined) {
        this.intFilteredNull = true
        this.$notify.info({
          title: '提示',
          message: '请输入连续天数'
        })
        return false
      }
      this.intFilteredNull = false
      return true
    },
    ruleInput (index) {
      console.log(index)
      switch (index) {
        case 1 :
          this.dateNull = false
          break
        case 2:
          this.intSettingNull = false
          break
        case 3:
          this.intFilteredNull = false
          break
      }
    },
    async getAlermData () {
      // 数据组装
      if (!this.ruleForm()) {
        return
      }
      this.tableLoading = true
      const queryInfo = {
        intSettingThreshold: this.form.intSettingThreshold,
        startDate: this.form.date[0],
        endDate: this.form.date[1],
        intFilteredThreshold: this.form.intFilteredThreshold
      }
      console.log(queryInfo)
      const { data: { data } } = await getAlermData(queryInfo)
      this.tableData = data
      this.tableTitle = []
      if (this.tableData.length !== 0) {
        const list = this.tableData[0].dataList
        if (list.length !== 0) {
          this.tableTitle = list.map(item => item.date)
        }
      }
      if (data.length === 0) {
        this.$notify.info({
          title: '提示',
          message: '设定时间段内无错误/异常数据'
        })
      }
      this.tableLoading = false
    },
    async getBaseData () {
      const { data: { data: data1 } } = await getAllNetCode()
      this.netCodeOptions = data1.map(item => ({ value: item, label: item }))
      const { data: { data: data2 } } = await getAllChanNum()
      this.chanNumOptions = data2.map(item => ({ value: item, label: item }))
      const { data: { data: data3 } } = await getAllChanCode()
      this.chanCodeOptions = data3.map(item => ({ value: item, label: item }))
    },
    async getNetCode () {
      const { data: { data } } = await getNetCode()
      this.netCode = data
    },
    getDefaultDate () {
      const date = new Date()// 当前时间
      const year = date.getFullYear() // 返回指定日期的年份
      const month = this.repairDate(date.getMonth() + 1)// 月
      const day = this.repairDate(date.getDate())// 日

      // 当前时间
      const endDate = year + '-' + month + '-' + day + ' '

      const date2 = new Date(date)
      date2.setDate(date2.getDate() - 6)
      const year2 = date2.getFullYear() // 返回指定日期的年份
      const month2 = this.repairDate(date2.getMonth() + 1)// 月
      const day2 = this.repairDate(date2.getDate())// 日
      const startDate = year2 + '-' + month2 + '-' + day2 + ' '
      const dateRange = [startDate, endDate]

      return dateRange
    },
    repairDate (i) {
      if (i >= 0 && i <= 9) {
        return '0' + i
      } else {
        return i
      }
    },
    queryData () {
      this.getAlermData()
    },
    clearFn () {
      this.form.intSettingThreshold = 1
      this.form.intFilteredThreshold = 1
      const dateRange = this.getDefaultDate()
      this.form.date = [dateRange[0], dateRange[1]]
      this.getAlermData()
    },
    async exportExcel () {
      if (!this.form.date) return this.$message.error('请指定导出范围~')

      this.$notify.info({
        title: '提示',
        message: '开始下载实时告警超标.xlsx文件，请稍候'
      })

      // 包裹多表数据变量定义
      const sheet = {
        data: [],
        colorCol: []
      }
      const header = ['台网', '', ...this.tableTitle, '总次数'] // 标题

      const colLength = this.tableTitle.length

      for (let i = 0; i < colLength; i++) {
        sheet.colorCol.push([])
      }

      console.log(this.tableData)

      this.tableData.forEach(item => {
        console.log(item)
        var row = []
        let obj1 = [item.netCode, '片区断记']
        let obj2 = item.dataList.map(date => date.areaBreakNum == null ? '-' : date.areaBreakNum)
        for (let i = 0; i < colLength; i++) {
          sheet.colorCol[i].push(item.dataList[i].status)
        }
        row = [...obj1, ...obj2, item.areaBreakTotal]
        sheet.data.push(row)
        row = []
        obj1 = ['', '片区延时']
        obj2 = item.dataList.map(date => date.areaDelayNum == null ? '-' : date.areaDelayNum)
        for (let i = 0; i < colLength; i++) {
          sheet.colorCol[i].push('')
        }
        row = [...obj1, ...obj2, item.areaBreakTotal]
        sheet.data.push(row)
      })

      import('@/utils/exportAlerm').then(excel => {
        excel.export_json_to_excel({
          // header: [header],
          header: header,
          data: sheet.data,
          filename: '实时告警超标',
          autoWidth: true,
          bookType: 'xlsx',
          colorCol: this.tableTitle,
          colorColData: sheet.colorCol
        })
      })
    },
    async exportDefaultExcel () {
      // 包裹多表数据变量定义
      const sheet = {
        data: [],
        colorCol: []
      }

      let tableTitle = []

      const dateRange = this.getDefaultDate()
      const queryInfo = {
        intSettingThreshold: 1,
        startDate: dateRange[0],
        endDate: dateRange[1],
        intFilteredThreshold: 1
      }
      console.log(queryInfo)
      const { data: { data } } = await getAlermData(queryInfo)

      if (data.length !== 0) {
        const list = data[0].dataList
        if (list.length !== 0) {
          tableTitle = list.map(item => item.date)
        }
      }

      const header = ['台网', '', ...tableTitle, '总次数'] // 标题

      const colLength = tableTitle.length

      for (let i = 0; i < colLength; i++) {
        sheet.colorCol.push([])
      }

      data.forEach(item => {
        console.log(item)
        var row = []
        let obj1 = [item.netCode, '片区断记']
        let obj2 = item.dataList.map(date => date.areaBreakNum == null ? '-' : date.areaBreakNum)
        for (let i = 0; i < colLength; i++) {
          sheet.colorCol[i].push(item.dataList[i].status)
        }
        row = [...obj1, ...obj2, item.areaBreakTotal]
        sheet.data.push(row)
        row = []
        obj1 = ['', '片区延时']
        obj2 = item.dataList.map(date => date.areaDelayNum == null ? '-' : date.areaDelayNum)
        for (let i = 0; i < colLength; i++) {
          sheet.colorCol[i].push('')
        }
        row = [...obj1, ...obj2, item.areaBreakTotal]
        sheet.data.push(row)
      })

      const date = new Date()// 当前时间
      const year = date.getFullYear() // 返回指定日期的年份
      const month = (date.getMonth() + 1 + '').padStart(2, '0')// 月
      const day = this.repairDate(date.getDate())// 日
      const hour = this.repairDate(date.getHours())
      const fileName = year + '-' + month + '-' + day + ' ' + hour + '时_实时告警超标'

      import('@/utils/exportAlerm').then(excel => {
        excel.export_json_to_excel({
          header: header,
          data: sheet.data,
          filename: fileName,
          autoWidth: true,
          bookType: 'xlsx',
          colorCol: tableTitle,
          colorColData: sheet.colorCol
        })
      })
    }
  }
}
</script>
<style lang="css" scoped>
/deep/ .el-table .cell {
  padding: 0;
}

/deep/ .el-table .el-table__cell {
  padding: 0;
}

/deep/ .el-table th.el-table__cell>.cell{
  padding: 10px;
}

.annotation-row{
  padding: 5px;
}
/deep/ .el-table__row > td .delay-row{
  border-top: 1px solid #EBEEF5;
}
.red{
  background:#f56c6c
}
.green{
  background:#00FF7F
}
.yellow{
  background:#ffeb9c
}
.blue{
  background:#4169e1
}

/deep/ .selectNull .el-input .el-input__inner {
  border: #F34E4EFF 1px solid!important;
}

/deep/ .inputNull{
  border: #F34E4EFF 1px solid!important;
}

/deep/ .numberNull .el-input__inner{
  border: #F34E4EFF 1px solid!important;
}
</style>
